package org.gwh.airagknowledge.api;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.gwh.airagknowledge.core.llm.impl.LlmFactory;
import org.gwh.airagknowledge.core.rag.RagQueryEngine;
import org.gwh.airagknowledge.entity.QAHistory;
import org.gwh.airagknowledge.repository.QAHistoryRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/qa")
@RequiredArgsConstructor
@Tag(name = "Question Answering", description = "APIs for question answering and retrieval")
public class QAController {

    private final RagQueryEngine ragQueryEngine;
    private final QAHistoryRepository qaHistoryRepository;
    private final LlmFactory llmFactory;

    @PostMapping("/ask")
    @Operation(summary = "Ask a question", description = "Ask a question to a specific knowledge base or directly to the LLM")
    public ResponseEntity<QAHistory> askQuestion(@RequestBody Map<String, Object> request) {
        // 1. 提取问题（必需参数）
        String question = (String) request.get("question");
        if (question == null || question.trim().isEmpty()) {
            throw new IllegalArgumentException("Question cannot be empty");
        }
        
        // 2. 提取知识库ID（可选参数）
        Long knowledgeBaseId = null;
        if (request.containsKey("knowledgeBaseId") && request.get("knowledgeBaseId") != null) {
            knowledgeBaseId = Long.valueOf(request.get("knowledgeBaseId").toString());
        }
        
        // 3. 提取温度参数（可选参数，默认0.1）
        Double temperature = request.containsKey("temperature") ? 
                Double.valueOf(request.get("temperature").toString()) : 0.1;
        
        // 4. 执行查询（根据是否有知识库ID自动选择查询方式）
        QAHistory qaHistory = ragQueryEngine.query(knowledgeBaseId, question, temperature);
        
        return ResponseEntity.ok(qaHistory);
    }
    
    @GetMapping("/providers")
    @Operation(summary = "Get LLM providers", description = "Get available LLM providers and current active provider")
    public ResponseEntity<Map<String, String>> getLlmProviders() {
        return ResponseEntity.ok(llmFactory.getAvailableProviders());
    }
    
    @PostMapping("/provider/{provider}")
    @Operation(summary = "Switch LLM provider", description = "Switch to a different LLM provider")
    public ResponseEntity<Map<String, Object>> switchLlmProvider(@PathVariable String provider) {
        boolean success = llmFactory.switchLlmProvider(provider);
        Map<String, Object> response = Map.of(
                "success", success,
                "currentProvider", llmFactory.getCurrentLlmService().getModelName()
        );
        return ResponseEntity.ok(response);
    }

    @GetMapping("/history")
    @Operation(summary = "Get QA history", description = "Retrieve the question answering history")
    public ResponseEntity<Page<QAHistory>> getQAHistory(Pageable pageable) {
        return ResponseEntity.ok(qaHistoryRepository.findAllByOrderByCreatedAtDesc(pageable));
    }

    @GetMapping("/history/search")
    @Operation(summary = "Search QA history", description = "Search the question answering history by question content")
    public ResponseEntity<Page<QAHistory>> searchQAHistory(
            @RequestParam String query,
            Pageable pageable) {
        return ResponseEntity.ok(
                qaHistoryRepository.findByQuestionContainingIgnoreCaseOrderByCreatedAtDesc(query, pageable));
    }

    @GetMapping("/history/{id}")
    @Operation(summary = "Get QA history entry", description = "Retrieve a specific QA history entry by its ID")
    public ResponseEntity<QAHistory> getQAHistoryById(@PathVariable Long id) {
        return qaHistoryRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
} 